package com.neusoft.bizcore.auth.repository.impl;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.auth.enums.AuthPermissionType;
import com.neusoft.bizcore.auth.model.AuthPermission;
import com.neusoft.bizcore.auth.model.QAuthPermission;
import com.neusoft.bizcore.auth.repository.CustomizedAuthPermissionRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedAuthPermissionRepositoryImpl extends AbstractRepository
        implements CustomizedAuthPermissionRepository {

    @Override
    public Page<AuthPermission> search(final Pageable pageable, final Searchable searchable) {
        final QAuthPermission qAuthPermission = QAuthPermission.authPermission;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AuthPermission> query = this.query().selectFrom(qAuthPermission);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return AuthPermission.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QAuthPermission qAuthPermission = QAuthPermission.authPermission;

        where.and(super.containsStr(qAuthPermission.code, searchable, "code"));
        where.and(super.containsStr(qAuthPermission.name, searchable, "name"));
        where.and(super.containsStr(qAuthPermission.contentType.appName, searchable, "appName"));
        where.and(
                super.equalsEnum(qAuthPermission.type, searchable, "type", value -> AuthPermissionType.valueOf(value)));
        return where;
    }
}
